package com.fz.song.web.controller;

import com.fz.song.framework.common.R;
import com.fz.song.framework.exceptions.ServerException;
import com.fz.song.web.entity.User;
import com.fz.song.web.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "幂等性demo-分布式锁")
@Slf4j
@RestController
@RequestMapping("idempotent")
public class DistributedController {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IUserService userService;


    @ApiOperation(value = "扣减库存", notes = "使用分布锁扣减库库存")
    @GetMapping("subStock")
    public R subStock(Integer id, Integer stock) throws InterruptedException {
        //创建锁
        RLock lock = redissonClient.getLock("sub_stock:" + id);
        //加锁
        lock.lock();
        try {
            User user = userService.getById(id);
            Integer stockDB = user.getStock();
            if (stockDB < stock) {
                throw new ServerException(1000, "库存不够,扣减失败");
            }
            user.setStock(stockDB - stock);
            userService.updateById(user);
            return R.ok("扣减库存");
        } catch (Exception e) {
            throw e;
        } finally {
            //释放锁(一定要释放)
            lock.unlock();
        }
    }


}
